package _hash;

import org.junit.Assert;
import org.junit.Test;

/**
 * https://leetcode.cn/problems/valid-anagram/description/
 * https://programmercarl.com/0242.%E6%9C%89%E6%95%88%E7%9A%84%E5%AD%97%E6%AF%8D%E5%BC%82%E4%BD%8D%E8%AF%8D.html
 * 题型：哈希法
 * ```
 * 242. 有效的字母异位词
 * 给定两个字符串 s 和 t ，编写一个函数来判断 t 是否是 s 的 字母异位词。
 *
 * 示例 1:
 *
 * 输入: s = "anagram", t = "nagaram"
 * 输出: true
 *
 * 示例 2:
 * 输入: s = "rat", t = "car"
 * 输出: false
 *
 *
 * 提示:
 *
 * 1 <= s.length, t.length <= 5 * 104
 * s 和 t 仅包含小写字母
 *
 *
 * 进阶: 如果输入字符串包含 unicode 字符怎么办？你能否调整你的解法来应对这种情况？
 * ```
 */
public class leetcode_242_Java {
    @Test
    public void test_1() {
        String s = "anagram", t = "nagaram";
        boolean actual = isAnagram(s, t);
        boolean expected = true;
        Assert.assertEquals(expected, actual);
    }

    @Test
    public void test_2() {
        String s = "rat", t = "car";
        boolean actual = isAnagram(s, t);
        boolean expected = false;
        Assert.assertEquals(expected, actual);
    }

    private boolean isAnagram(String s, String t) {
        // S - N + M
        // T - 1
        // a-z
        // array[] ++
        // array[] --
        // array[i]!= 0 => false
        int[] array = new int['z' - 'a' + 1];
        char[] a = s.toCharArray();
        char[] b = t.toCharArray();
        for (int i = 0; i <= a.length - 1; i++) {
            array[a[i] - 'a'] = array[a[i] - 'a'] + 1;
        }
        for (int i = 0; i <= b.length - 1; i++) {
            array[b[i] - 'a'] = array[b[i] - 'a'] - 1;
        }

        for (int v : array) {
            if (v != 0) {
                return false;
            }
        }
        return true;
    }
}
